package org.wltea.analyzer.core;

import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.wltea.analyzer.dic.Monitor;

public class PunctuationSegmenter implements ISegmenter {
    //子分词器标签
    static final String SEGMENTER_NAME = "PUNCTUATION_SEGMENTER";

    //日志
    private static final Logger logger = ESLoggerFactory.getLogger(Monitor.class.getName());


    /*
     * 符号的开始位置，
     * 同时作为子分词器状态标识
     * 当start > -1 时，标识当前的分词器正在处理字符
     */
    private int start;
    /*
     * 记录词元结束位置
     */
    private int end;

    PunctuationSegmenter() {
        this.start = -1;
        this.end = -1;
    }


    @Override
    public void analyze(AnalyzeContext context) {
        boolean bufferLockFlag = false;
        //处理英文字母
        bufferLockFlag = this.processPunctuation(context) || bufferLockFlag;

        //判断是否锁定缓冲区
        if (bufferLockFlag) {
            context.lockBuffer(SEGMENTER_NAME);
        } else {
            //对缓冲区解锁
            context.unlockBuffer(SEGMENTER_NAME);
        }
    }

    @Override
    public void reset() {
        this.start = -1;
        this.end = -1;
    }


    private boolean processPunctuation(AnalyzeContext context) {
        boolean needLock = false;

        if (this.start == -1) {//当前的分词器尚未开始处理标点符号
            if (CharacterUtil.CHAR_PUNC == context.getCurrentCharType()) {
                //记录当前指针位置为结束位置
                //输出词元
                this.end = context.getCursor();
                this.start = context.getCursor();
                Lexeme newLexeme = new Lexeme(context.getSegmentBuff(), context.getBufferOffset(), this.start, this.end - this.start + 1, Lexeme.TYPE_PUNC);
                context.addLexeme(newLexeme);
                this.start = -1;
                this.end = -1;
            }
        }

        //判断缓冲区是否已经读完
        if (context.isBufferConsumed() && (this.start != -1 && this.end != -1)) {
            //缓冲以读完，输出词元
            Lexeme newLexeme = new Lexeme(context.getSegmentBuff(), context.getBufferOffset(), this.start, this.end - this.start + 1, Lexeme.TYPE_PUNC);
            context.addLexeme(newLexeme);
            this.start = -1;
            this.end = -1;
        }

        //判断是否锁定缓冲区
        if (this.start == -1 && this.end == -1) {
            //对缓冲区解锁
            needLock = false;
        } else {
            needLock = true;
        }
        return needLock;
    }
}
